package com.vip.jwt.entity;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.stream.Collectors;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

/**
 * <p>
 * 角色菜单关联表
 * </p>
 *
 * @author vip
 * @since 2021-05-04
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("t_role_menu")
@ApiModel(value="RoleMenu对象", description="角色菜单关联表")
public class RoleMenu implements Serializable {

    private static final long serialVersionUID=1L;

    @ApiModelProperty(value = "ID")
    private String id;

    @ApiModelProperty(value = "角色ID")
    private String roleId;

    @ApiModelProperty(value = "菜单ID")
    private String menuId;

    /**
     * 根据关联表数据在列表中获取，然后向上遍历树到根节点
     * @param menus
     * @param roleMenus
     * @return
     */
    public static List<String>[] findByIds(List<Menu> menus,List<RoleMenu> roleMenus){
        List<String>[] listsArr = new ArrayList[roleMenus.size()];
        for(int i=0;i<roleMenus.size();i++){
            RoleMenu roleMenu = roleMenus.get(i);
            String menuId = roleMenu.getMenuId();
            List<Menu> findMenus = findById(menus, menuId);
            List<String> findMenuIds = findMenus.stream().map(Menu::getId).collect(Collectors.toList());
            listsArr[i] = findMenuIds;
        }
        return listsArr;
    }

    /**
     * 根据ID在列表中获取，然后向上遍历树到根节点
     * @param menus 所有的菜单
     * @param menuId
     * @return
     */
    public static List<Menu> findById(List<Menu> menus, String menuId){
        Deque<Menu> systemMenus = new ArrayDeque<>();
        String parentId = menuId;
        while (true){
            Menu findMenu = null;
            for(int i=0;i<menus.size();i++){
                Menu menu = menus.get(i);
                if(StrUtil.equals(menu.getId(),parentId)){
                    findMenu = menu;
                }
            }
            if(ObjectUtil.isNotNull(findMenu)){
                systemMenus.addFirst(findMenu);
                parentId = findMenu.getParentId();
            }else{
                break;
            }
        }
        return systemMenus.stream()
                .map(v->new Menu(v.getId(), v.getTitle(), v.getUrl(), v.getIcon(), v.getSort(), v.getParentId()))
                .collect(Collectors.toList());
    }

}
